<template>
  <div class="publish-content">
    <baseTable :page.sync="page" :cols="tableCols" :data="tableData">
      <template #head>
        <div class="head">
          <div class="search">
            <el-cascader
              v-model="areaInfo"
              :options="cityList"
              :props="casxaderProps"
              placeholder="体检城市"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
            ></el-cascader>
            <el-select v-model="params.year" placeholder="体检年份" clearable>
              <el-option
                v-for="item in yearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select v-model="params.status" placeholder="发布状态" clearable>
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-input
              placeholder="请输入任务名称、体系名称"
              v-model="params.keywords"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search cursor-pointer"
                @click="getTaskListData"
              ></i>
            </el-input>
          </div>
          <div>
            <el-button
              v-if="currentUser?.hasPermission(PERMISSIONS.任务管理新增)"
              size="small"
              type="primary"
              icon="el-icon-plus"
              @click="goEdit(null)"
              >{{
                currentUser?.getButtonName(PERMISSIONS.任务管理新增)
              }}</el-button
            >
          </div>
        </div>
      </template>
      <template #cols>
        <el-table-column label="填报进度">
          <template slot-scope="scope">
            {{ scope.row.completeCount }}/{{ scope.row.allCount }}</template
          >
        </el-table-column>
        <el-table-column label="发布状态">
          <template slot-scope="scope">
            <el-tag
              :type="tagTyep(scope.row.status)"
              size="small"
              disable-transitions
              >{{ scope.row.status | statusFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-link
              slot="reference"
              class="mr-10"
              type="primary"
              @click="goEdit(scope.row, false)"
              :underline="false"
              v-if="currentUser?.hasPermission(PERMISSIONS.任务管理详情)"
              >{{
                currentUser?.getButtonName(PERMISSIONS.任务管理详情)
              }}</el-link
            >
            <el-link
              slot="reference"
              v-if="
                scope.row.status == 0 &&
                currentUser?.hasPermission(PERMISSIONS.任务管理编辑)
              "
              type="primary"
              class="mr-10"
              @click="goEdit(scope.row, true)"
              >{{
                currentUser?.getButtonName(PERMISSIONS.任务管理编辑)
              }}</el-link
            >

            <el-popconfirm
              v-if="scope.row.status == 0"
              title="确定删除该任务？"
              @confirm="handleRemove(scope.row.pkid, scope.$index)"
            >
              <el-link
                v-if="currentUser?.hasPermission(PERMISSIONS.任务管理删除)"
                slot="reference"
                type="danger"
                :underline="false"
                >{{
                  currentUser?.getButtonName(PERMISSIONS.任务管理删除)
                }}</el-link
              >
            </el-popconfirm>
            <el-popconfirm
              v-if="scope.row.status == 1"
              title="确定取消发布该任务？"
              @confirm="handlePublish(scope.row.pkid, 0)"
            >
              <el-link
                v-if="currentUser?.hasPermission(PERMISSIONS.任务管理取消发布)"
                slot="reference"
                type="danger"
                :underline="false"
                >{{
                  currentUser?.getButtonName(PERMISSIONS.任务管理取消发布)
                }}</el-link
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </template>
    </baseTable>
    <el-dialog title="新建任务" :visible.sync="dialogVisible" width="30%">
      <el-form
        label-position="left"
        label-width="150px"
        :model="baseForm"
        :rules="baseFormRules"
        ref="baseFormRef"
        class=""
      >
        <!-- :disabled="!isEdit" class="flex justify-between flex-wrap"-->
        <el-form-item label="任务名称：" prop="taskName">
          <el-input
            v-model.trim="baseForm.taskName"
            style="width: 100%"
            :disabled="dialogDisabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="指标体系名称：" prop="indexName">
          <el-select
            style="width: 100%"
            filterable
            v-model="baseForm.indexName"
            placeholder="请选择指标体系"
            @change="handleChangeBaseId"
            :disabled="dialogDisabled"
          >
            <el-option
              v-for="item in quotaSystemList"
              :key="item.pkid"
              :label="item.indexName"
              :value="item.indexName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体检区县：" prop="regionId">
          <el-select
            v-model="regionIds"
            style="width: 100%"
            @change="handleChangeAreaClick"
            multiple
            :disabled="!baseForm.indexName || dialogDisabled"
          >
            <el-option
              v-for="item in regionOptions"
              :key="item.pkid"
              :label="item.areaName"
              :value="item.areaCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体检年份：" prop="year">
          <el-input
            v-model="baseForm.year"
            style="width: 100%"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="完成时限：" prop="completeTime">
          <el-date-picker
            style="width: 100%"
            value-format="yyyy-MM-dd"
            v-model="baseForm.completeTime"
            type="date"
            placeholder="选择日期"
            :disabled="dialogDisabled"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务描述：" prop="description">
          <el-input
            style="width: 100%"
            v-model="baseForm.description"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            :disabled="dialogDisabled"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          class="cancel1"
          @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          size="small"
          class="save1"
          @click="handleSave(0)"
          v-if="
            !dialogDisabled &&
            currentUser?.hasPermission(PERMISSIONS.任务管理保存)
          "
          :loading="saveLoading"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.任务管理保存) }}
        </el-button>
        <el-button
          v-loading="loading"
          type="primary"
          size="small"
          class="publish1"
          v-if="
            !dialogDisabled &&
            baseForm.status == 0 &&
            currentUser?.hasPermission(PERMISSIONS.任务管理发布)
          "
          @click="handlePublish(baseForm.pkid, 1)"
        >
          {{ currentUser?.getButtonName(PERMISSIONS.任务管理发布) }}
        </el-button>
        <!--        <el-button-->
        <!--          v-loading="loading"-->
        <!--          type="primary"-->
        <!--          size="small"-->
        <!--          v-if="dialogDisabled && baseForm.status == 1"-->
        <!--          plain-->
        <!--          @click="handlePublish(baseForm.pkid, 0)"-->
        <!--          >取消发布</el-button-->
        <!--        >-->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import baseTable from '@c/base-table'
import {
  queryBaseIndexPull,
  queryTask,
  addTask,
  deleteTask,
  publishTask,
  queryBaseIndexList,
} from '@api/city-index'
import { queryArea, queryTaskArea } from '@api/question'
import { isFunction } from 'lodash'
import { PERMISSIONS } from '@/common/user'
import { mapGetters } from 'vuex'
export default {
  name: 'publish',
  components: { baseTable },
  computed: {
    ...mapGetters(['currentUser', 'user']),
  },
  data() {
    return {
      PERMISSIONS,
      loading: false,
      isXq: false,
      page: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      params: {
        areaId: null,
        districtId: null,
        year: null,
        keywords: null,
        status: null,
      },
      tableData: [],
      tableCols: [
        {
          prop: 'taskName',
          label: '任务名称',
        },
        {
          prop: 'description',
          label: '任务描述',
        },
        {
          prop: 'indexName',
          label: '指标体系名称',
        },
        {
          prop: 'areaName',
          label: '体检城市',
        },
        {
          prop: 'year',
          label: '体检年份',
        },
        {
          prop: 'createUserName',
          label: '创建人',
        },
        {
          prop: 'createTime',
          label: '发布时间',
          width: 160,
        },
        {
          prop: 'completeTime',
          label: '完成时限',
          width: 160,
        },
      ],
      cityList: [],
      casxaderProps: {
        value: 'areaCode',
        label: 'areaName',
        checkStrictly: true,
        children: 'children',
      },
      areaInfo: [],
      yearOptions: [
        {
          value: '2021',
          label: '2021年',
        },
        {
          value: '2022',
          label: '2022年',
        },
        {
          value: '2023',
          label: '2023年',
        },
        {
          value: '2024',
          label: '2024年',
        },
      ],
      statusList: [
        {
          value: 1,
          label: '已发布',
        },
        {
          value: 0,
          label: '未发布',
        },
      ],
      quotaSystemList: [],
      saveLoading: false,
      dialogVisible: false,
      dialogDisabled: false,
      regionOptions: [],
      regionIds: [],
      baseForm: {
        taskName: '',
        regionId: '',
        year: '',
        description: '',
        status: 0,
        completeTime: '',
      },
      baseFormRules: {
        taskName: [
          { required: true, trigger: 'blur', message: '请填写任务名称' },
        ],
        regionId: [
          { required: true, trigger: 'change', message: '请选择体检区县' },
        ],
        indexName: [
          { required: true, trigger: 'change', message: '请选择指标体系' },
        ],
        completeTime: [
          { required: true, trigger: 'blur', message: '请选择结束时间' },
        ],
      },
    }
  },
  created() {},
  mounted() {
    this.getTaskListData()
    this.getIndexPullList()
    queryArea({
      districtFlag: 'true',
    }).then((res) => {
      if (res.success) {
        const node = this.findNodeById(res.data, this.user.refId)
        this.cityList = this.removeChildrenAtLevel([node], 1)[0].children
      }
    })
  },
  methods: {
    findNodeById(tree, targetId) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的ID是否为目标ID
        if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
          // 如果是的话，返回当前节点
          return tree[i]
        }

        // 如果当前节点有子节点，则递归在子节点中查找
        if (tree[i].children && tree[i].children.length > 0) {
          const foundNode = this.findNodeById(tree[i].children, targetId)
          // 如果在子节点中找到了，则返回找到的节点
          if (foundNode !== undefined) {
            return foundNode
          }
        }
      }

      // 如果在树中没有找到目标ID，则返回undefined
      return undefined
    },
    handleChangeBaseId(item) {
      // console.log(11222)
      const find = this.quotaSystemList.find((i) => i.indexName === item)
      if (find) {
        // const type = find.type
        // let f
        // if (type === 'city') {
        //   f = this.cityList.find((i) => i.areaCode === find.areaId)
        // } else {
        //   f = this.cityList[0].children.find((i) => i.areaCode === find.areaId)
        // }
        queryTaskArea(find.pkid).then((res) => {
          if (res.success) {
            this.regionOptions = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        Object.assign(this.baseForm, {
          year: find.year,
          // areaName: f?.areaName,
          baseId: find.pkid,
        })
        // console.log(this.baseForm)
      }
    },
    handleChangeAreaClick() {
      this.baseForm.regionId = this.regionIds.toString()
    },
    handleChangeArea(val) {
      this.page.pageIndex = 1
      if (val.length === 1) {
        this.params.districtId = val[0]
        this.params.areaId = null
      } else {
        this.params.districtId = null
        this.params.areaId = val[val.length - 1]
      }
      // console.log(222)
      // this.getTaskListData()
    },
    removeChildrenAtLevel(tree, targetLevel) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的level是否为目标level
        if (tree[i].level === targetLevel) {
          // 如果是的话，移除children属性
          delete tree[i].children
        }

        // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
        if (tree[i].children && tree[i].children.length > 0) {
          this.removeChildrenAtLevel(tree[i].children, targetLevel)
        }
      }

      return tree
    },
    getIndexPullList() {
      queryBaseIndexList({
        pageIndex: 1,
        pageSize: 999,
      }).then((res) => {
        if (res.success) {
          // console.log(res.data)
          this.quotaSystemList = res.data.list
        }
      })
    },
    getTaskListData() {
      queryTask({ ...this.page, ...this.params }).then((res) => {
        if (res.success) {
          this.tableData = res.data.list
          this.page.total = res.data.count
        }
      })
    },
    handleSave(cb) {
      this.$refs.baseFormRef.validate((valid) => {
        if (valid) {
          this.saveLoading = true
          // console.log(this.baseForm)
          addTask(this.baseForm)
            .then((res) => {
              if (res.success) {
                this.$message.success('保存成功！')
                // this.dialogVisible = false
                // this.getTaskListData()
                if (isFunction(cb)) {
                  cb(res.data)
                } else {
                  this.baseForm.pkid = res.data
                  this.getTaskListData()
                }
              }
            })
            .finally(() => {
              this.saveLoading = false
            })
        }
      })
    },

    handleRemove(pkid) {
      deleteTask(pkid).then((res) => {
        if (res.success) {
          this.$message.success('删除成功！')
          this.getTaskListData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handlePublish(pkid, status) {
      const publish = (pkid) => {
        publishTask(pkid, status).then((res) => {
          if (res.success) {
            if (status == 1) {
              this.$message.success('发布成功！')
              this.dialogVisible = false
            } else {
              this.$message.success('取消发布成功！')
              this.dialogVisible = false
            }
            this.getTaskListData()
          } else {
            this.$message.error(res.message)
          }
        })
      }
      if (!pkid) {
        this.handleSave(publish)
      } else {
        publish(pkid)
      }
    },
    goEdit(item, isEdit) {
      if (item) {
        if (isEdit) {
          //
          this.baseForm = item
          this.dialogVisible = true
          this.dialogDisabled = false
        } else {
          // 详情
          this.baseForm = item
          this.dialogDisabled = true
          this.dialogVisible = true
        }

        queryArea({
          level: 1,
        })
          .then((res) => {
            if (res.success) {
              const data = res.data[0]?.children || []
              this.regionOptions = data.map((i) => {
                i.children = []
                return i
              })
            } else {
              this.$message.error(res.message)
            }
          })
          .finally(() => {
            this.$nextTick(() => {
              if (item.regionId) {
                this.regionIds = item.regionId.split(',')
              }
            })
          })
      } else {
        //
        this.dialogDisabled = false
        this.dialogVisible = true
        this.baseForm = {
          taskName: '',
          city: '',
          year: '',
          description: '',
          status: 0,
          completeTime: '',
          baseId: '',
          indexName: '',
          regionId: '',
        }
        this.regionIds = []
        this.regionOptions = []
        this.$nextTick(() => {
          this.$refs.baseFormRef.clearValidate()
        })
      }
    },
    tagTyep(val) {
      let type = ''
      switch (val) {
        case 0:
          type = 'danger'
          break
        case 1:
          type = ''
          break
        case 2:
          type = 'warning'
          break
        case 3:
          type = 'success'
          break
      }
      return type
    },
  },
  watch: {
    page(newVal, oldVal) {
      if (
        !(
          newVal.pageIndex === oldVal.pageIndex &&
          newVal.pageSize === oldVal.pageSize
        )
      ) {
        this.getTaskListData()
      }
    },
    params: {
      handler: function () {
        {
          if (this.page.pageIndex === 1) {
            this.getTaskListData()
          } else {
            this.page.pageIndex = 1
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.publish-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  border-radius: 10px;
  box-sizing: border-box;

  .head {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
  }

  .search {
    .el-cascader {
      margin-right: 10px;
    }

    .el-select {
      margin-right: 10px;
      width: 120px;
    }

    .el-input {
      width: 230px;
    }
  }
}

.cancel1 {
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid #e7f0ff;
  font-weight: 400;
  font-size: 16px;
  color: #8894a8;
}

.save1 {
  //background: #10a6dd;
  border-radius: 4px;
  //color: #ffffff;
}

.publish1 {
  //background: #ffffff;
  border-radius: 4px;
  //color: #10a6dd;
  //border: 1px solid #10a6dd;
}

// ::v-deep {
//   .el-table__row {
//     height: 65px;
//   }
// }
</style>
